package org.sam.swing.table.defaultImpl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.swing.JOptionPane;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.table.TableColumnExt;
import org.sam.swing.action.JSFileExportActionListener;
import org.sam.swing.table.JSTableColumnModel;
import org.sam.swing.table.JSTableModel;
import org.sam.swing.table.action.JSTableAction;

/**
 * 使用tableModel设置好的属性,生成默认的导出功能
 * 
 * @author sam
 *
 */
public class DefaultExportListenerActionImpl implements JSFileExportActionListener, JSTableAction {

	/**
	 * 当前操作的表格对象
	 */
	private JXTable table;

	/**
	 * {@inheritDoc} 设置当前table上下文
	 */
	@Override
	public JXTable getTable() {
		return this.table;
	}

	/**
	 * {@inheritDoc} 设置前操作的表格对象
	 */
	@Override
	public void setTable(JXTable table) {
		this.table = table;
	}

	/**
	 * 是否导出表头
	 */
	private boolean exportHeader = true;

	/**
	 * 是否导出报表表头
	 * 
	 * @return
	 */
	public boolean getExportHeader() {
		return this.exportHeader;
	}

	/**
	 * 设置是否导出表头
	 * 
	 * @param exportHeader
	 */
	public void setExportHeader(boolean exportHeader) {
		this.exportHeader = exportHeader;
	}

	/**
	 * 默认的文件保存名称
	 */
	private String fileName;

	/**
	 * 默认的文件保存名称
	 * 
	 * @return
	 */
	public String getFileName() {
		return fileName;
	}

	/**
	 * 默认的文件保存名称
	 * 
	 * @param fileName
	 */
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	/**
	 * 使用tableModel设置好的属性,生成默认的导出功能
	 * 
	 * @param name 文件名称
	 */
	public DefaultExportListenerActionImpl(String name) {
		this.setFileName(name);
	}
	
	/**
	 * 使用tableModel设置好的属性,生成默认的导出功能
	 * @param table 表格
	 * @param name 文件名称
	 */
	public DefaultExportListenerActionImpl(JXTable table ,String name) {
		this.setTable(table);
		this.setFileName(name);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public File initFile() throws Exception {
		if (!StringUtils.isEmpty(this.getFileName())) {
			return new File(System.getProperty("user.dir") + "/" + this.getFileName() + ".xls");
		}
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void afterOpen(File file) throws Exception {
		if (file == null)
			throw new Exception("未设置保存文件");

		this.exportTableData(file);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void afterDone() throws Exception {
		JOptionPane.showMessageDialog(null, "导出完成");
	}

	/**
	 * 导出当前表格显示的数据集合
	 */
	protected void exportTableData(File file) {

		try (HSSFWorkbook doc = new HSSFWorkbook()) {
			JSTableModel<?> model = (JSTableModel<?>) this.getTable().getModel();
			JSTableColumnModel colModel = (JSTableColumnModel) this.getTable().getColumnModel();
			List<TableColumnExt> columnList = colModel.getVisibleDataColumns();

			if (columnList == null || columnList.isEmpty())
				return;

			TableColumnExt[] columns = columnList.toArray(new TableColumnExt[columnList.size()]);

			HSSFSheet sheet = doc.createSheet();

			// 导出表头
			int index = 0;
			if (this.getExportHeader()) {
				HSSFRow row = sheet.createRow(index);
				for (int j = 0; j < columns.length; j++) {
					HSSFCell cell = row.createCell(j);
					String valueAt = columns[j].getHeaderValue() == null
							? (columns[j].getTitle() == null ? "" : columns[j].getTitle().toString())
							: columns[j].getHeaderValue().toString();
					cell.setCellValue(valueAt);
				}
				index++;
			}

			for (int i = 0, iCount = this.getTable().getRowCount(); i < iCount; i++) {
				int iRow = this.getTable().convertRowIndexToModel(i);
				HSSFRow row = sheet.createRow(index);
				// 直接写入
				for (int j = 0; j < columns.length; j++) {
					HSSFCell cell = row.createCell(j);
					Object valueAt = model.getValueAt(iRow, columns[j].getModelIndex());
					cell.setCellValue(valueAt == null ? "" : getTableCellValue(valueAt));
				}
				index++;
			}

			doc.write(file);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	
	/**
	 * 格式化日期时间对象专用
	 */
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	/**
	 * 数据转换,遇到date单独处理一下
	 * @param value
	 * @return
	 */
	protected String getTableCellValue(Object value){
		if (Objects.isNull(value))
			return "";
		
		if (value instanceof Date){
			return sdf.format(value);
		}
		
		return value.toString();
	}
}
